package com.threeidiots.findit.multimedia;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import com.threeidiots.findit.R;

/**
 * use the system camera
 * @author Elvis
 *
 */
public class CameraActivity extends Activity {
	   
	private final String TAG = "CameraActivity";
    private final int MEDIA_TYPE_IMAGE = 1;
    
    private final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private Uri fileUri = null;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        
    }
    
    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data){
    	if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE){
    		if (resultCode == RESULT_OK) {
    			
				Toast.makeText(this, "Image saved to:\n"+fileUri,
								Toast.LENGTH_LONG).show();
				try {
					this.finalize();
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
//				try {
//    				saveMyBitmap();
//    			} catch (IOException e) {
//    				// TODO Auto-generated catch block
//    				e.printStackTrace();
//    			}
			}else if(resultCode == RESULT_CANCELED){
				
			}else {
				
			}
    	}
    	this.finish();
    }
	private Uri getOutputMediaFileUri(int type) {
		// TODO Auto-generated method stub
		return Uri.fromFile(getOutputMediaFile(type));
	}

	private File getOutputMediaFile(int type) {
		// TODO Auto-generated method stub
		File mediaStorageDir = new File(
				Environment.getExternalStorageDirectory().toString()
				,getString(R.string.app_dir)+"/pictures");
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(TAG, "fail to create directory");
				return null;
			}
		}
		
		String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		File mediaFile;
		if (type==MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath()
								+ File.separator 
								+ "IMG_" + timestamp + ".jpg");
			
			Intent back = new Intent();
			back.putExtra("filename", mediaFile.toString());
			this.setResult(1, back);
			return mediaFile;
		}else{
			return null;
		}
		
	}
	

	private void saveMyBitmap() throws IOException {
		File originalFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
		Bitmap bmp = decodeFile(originalFile);
		 
		String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 
		File f = new File(Environment.getExternalStorageDirectory().toString()
				,getString(R.string.app_dir)+"/pictures/IMG_"+ timestamp + ".jpg");
		f.createNewFile();
		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		 
		//BitmapFactory.Options options=new BitmapFactory.Options();
		        //options.inSampleSize = 10;
		//options.inTempStorage = new byte[16*1024];
		 
		//Bitmap bmp = BitmapFactory.decodeFile("/sdcard/pic/sd.jpg");
		//Bitmap bmp = BitmapFactory.decodeFile("/sdcard/pic/ll.jpg", options);
		//bmp = Bitmap.createScaledBitmap(bmp, 800, 480, true);
		 
		bmp.compress(Bitmap.CompressFormat.JPEG, 30, fOut);
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
		 
		//decodes image and scales it to reduce memory consumption
		private Bitmap decodeFile(File f){
		   try {
		       //Decode image size
		       BitmapFactory.Options o = new BitmapFactory.Options();
		       o.inJustDecodeBounds = true;
		       BitmapFactory.decodeStream(new FileInputStream(f),null,o);

		       //The new size we want to scale to
		       final int REQUIRED_HEIGHT=800;
		       final int REQUIRED_WIDTH=480;

		       //Find the correct scale value. It should be the power of 2.
		       int width_tmp=o.outWidth, height_tmp=o.outHeight;
		       
		       System.out.println(width_tmp+"  "+height_tmp);
		       Log.w(TAG, (width_tmp+"  "+height_tmp));
		       
		       int scale=1;
		       while(true){
		           if(width_tmp/2<REQUIRED_WIDTH && height_tmp/2<REQUIRED_HEIGHT)
		               break;
		           width_tmp/=2;
		           height_tmp/=2;
		           scale++;
		           
		           Log.w(TAG, scale+"''"+width_tmp+"  "+height_tmp);
		       }

		       //Decode with inSampleSize
		       BitmapFactory.Options o2 = new BitmapFactory.Options();
		       o2.inSampleSize=scale;
		       return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		   } catch (FileNotFoundException e) {}
		   return null;
		}
}
